package com.aaa.yq127.controller;


import com.aaa.yq127.dao.impl.StaffDaoImpl;
import com.aaa.yq127.util.Result;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@WebServlet("/staff/*")
public class StaffServlet extends HttpServlet {
    public final StaffDaoImpl staffDao = new StaffDaoImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        int i = uri.lastIndexOf("/");
        String s = uri.substring(i + 1);
        switch (s){
            case "selectSta":
                selectSta(req,resp);
                break;
            case "deleteSta":
                deleteSta(req,resp);
                break;
            case "updateSta":
                updateSta(req,resp);
            default:
                break;
        }
    }



    protected void updateSta(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String id = req.getParameter("id");


    }

    /**
     * 删除一条数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void deleteSta(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String id = req.getParameter("id");
        int i = staffDao.delStaff(Integer.parseInt(id));
        if (i>0){
            req.getRequestDispatcher("/selstaff.jsp").forward(req,resp);
        }
    }


    /**
     * 查询全部
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void selectSta(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求的编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //数据操作
        List<Map<String, Object>> maps = staffDao.selStaff();
        //获取你总共有几行数据
        int i = maps.size();
        //调用你的封装类，变成一个json类型的字符串
        Result result = new Result(i,maps);
        String s = JSON.toJSONString(result);
        //获得一个输出流
        PrintWriter writer = resp.getWriter();
        //把这个json字符串写出去
        writer.write(s);
    }

}
